package com.fenghongzhang.day008;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main2Activity extends AppCompatActivity {

    private static final String TAG = "Main2Activity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //判断用户手机的版本.
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //2,动态申请一个权限
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }else{
            //是否挂载,是否插入的意思
            writeFile();
        }

    }

    //3,请求权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //请求码是100,并且用户点击的是同意
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "同意", Toast.LENGTH_SHORT).show();
        }else{
            finish();
        }
    }

    //4 写
    public void write(View view) {
        writeFile();

    }

    //写---c + s + m
    // alt + s + m
    private void writeFile() {
        //是否挂载,是否插入的意思
        String externalStorageState = Environment.getExternalStorageState();
//        Log.i(TAG, "write: "+externalStorageState);
        //sd的跟路径
        File file = Environment.getExternalStorageDirectory();
//        Log.i(TAG, "write: "+file.getAbsolutePath());

        //已经挂载
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {

//            new FileOutputStream("c/dd/a.txt");
            //storage/emulated/0/one.txt
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(new File(file, "one.txt"));
                fileOutputStream.write("哈哈".getBytes());
                fileOutputStream.flush();
                fileOutputStream.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void read(View view) {
    }
}
